package com.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.guestbook.dao.AdminDAO;
import com.guestbook.dao.impl.AdminDAOJdbc;
import com.tools.StringUtil;

public class AdminUserServlet extends HttpServlet {

	private static final long serialVersionUID = 7080068621990275611L;

	public void login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String message="";
		if(StringUtil.validateIsNull(username)||StringUtil.validateIsNull(password)){
			message="用户名或密码不能为空";
			request.setAttribute("guestbook.admin.login.message", message);
			request.getRequestDispatcher("/admin/loginFail.jsp").forward(request, response);
		}else{
			AdminDAO dao=new AdminDAOJdbc();
			if(dao.getAdmin(username, password)==null){
				message="对不起，用户名或密码不正确，请重新输入!";
				request.setAttribute("guestbook.admin.login.message", message);
				request.getRequestDispatcher("/admin/loginFail.jsp").forward(request, response);
			}else{
				HttpSession session=request.getSession();
				session.setAttribute("guestbook.admin.username", username);
				response.sendRedirect(request.getContextPath()+"/admin/secure/manage?q=list");
			}
		}
	}
	
	public void logout(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		HttpSession session=request.getSession();
		session.removeAttribute("guestbook.admin.username");
		response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method=request.getParameter("q");
		if(method!=null && method.equals("login")){
			login(request, response);
		}else{
			logout(request, response);
		}
	}
}
